package com.navi.loaddata.loadService.impl.baseData.cell2;

import com.navi.loaddata.core.errorLog.ErrorLog;
import com.navi.loaddata.core.etlException.ETLException;
import com.navi.loaddata.core.gpEntity.MArrayParamD;
import com.navi.loaddata.core.gpEntity.MOpeD;
import com.navi.loaddata.core.gpEntity.MParamD;
import com.navi.loaddata.core.mesEntity.MesNode;
import com.navi.loaddata.core.mesEntity.MesProcessoperationspec;
import com.navi.loaddata.core.mesEntity.MesProducthistory;
import com.navi.loaddata.core.mesEntity.MesProductspec;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.oracleEntity.cell2.EtlCell2ProductV;
import com.navi.loaddata.core.oracleEntity.cell2.EtlCell2StepV;
import com.navi.loaddata.core.repository.impl.GreenPlumRepositoryImpl;
import com.navi.loaddata.core.repository.impl.MesRepositoryImpl;
import com.navi.loaddata.core.util.LoggerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.navi.loaddata.core.constant.GenericDef.OTHER;
import static com.navi.loaddata.core.constant.GenericDef.SHOP_OC;

@Service
@Transactional(transactionManager = "mesPlatformTransactionManager",
        rollbackFor = {RuntimeException.class, Exception.class})
public class LoadMesBaseDataServiceCELL2 {

    @Autowired
    private MesRepositoryImpl daomes;
    @Autowired
    private GreenPlumRepositoryImpl dao2;

    @Autowired
    private ProcessBaseDataServiceCELL2 processBaseDataService;
    private static final Logger logger = LoggerFactory.getLogger(LoadMesBaseDataServiceCELL2.class);

    public List<MesNode> loadMesNode(String flowName) {
        String hql = "from MesNode where processflowname = '" + flowName + "' order by nodeid ";
        return daomes.find(MesNode.class, hql);
    }
    public Map<String, MesNode> getMesNodeMap(String flowName) {
        Map<String, MesNode> mesNodeMap = new HashMap<>();
        List<MesNode> mesNodeList = loadMesNode(flowName);
        boolean getStart = false;
        boolean getEnd = false;
        for (int i = 0; i < mesNodeList.size(); i++) {
            if ("Start".equals(mesNodeList.get(i).getNodetype())) {
                getStart = true;
            } else if ("End".equals(mesNodeList.get(i).getNodetype())) {
                getEnd = true;
            } else {
                if (getStart & !getEnd) {
                    mesNodeMap.put(mesNodeList.get(i).getNodeattribute1(), mesNodeList.get(i));
                }
            }
        }
        return mesNodeMap;
    }


    public List<MesProcessoperationspec> loadAllStep(String shopName) {
        String hql = "from MesProcessoperationspec where 1=1 ";
        if (!StringUtils.isEmpty(shopName)) {
            hql += " and subfactoryname = '" + shopName + "'";
        }
        return daomes.find(MesProcessoperationspec.class, hql);
    }

    public List<EtlCell2StepV> loadAllMesFinalStep(String shopName, int errorProcessArrayStepV) throws ETLException {
        List<MesProcessoperationspec> mesProcessoperationspecList = loadAllStep(shopName);
        Map<String, MesNode> mesNodeMap = getMesNodeMap("MA1495A1ANK1");

        List<EtlCell2StepV> etlCellStepVList = new ArrayList<>();
        try {
            Map<String, Boolean> mesProcessoperationspecMap = new HashMap<>();
            mesProcessoperationspecList.forEach(o -> {
                String opeName = o.getProcessoperationname();
                if (null == mesProcessoperationspecMap.get(opeName)) {
                    mesProcessoperationspecMap.put(opeName, true);
                    if (!(opeName.length() > 5 && "D".equals(opeName.substring(5, 6)))) {
                        EtlCell2StepV etlCellStepV = new EtlCell2StepV();
//                        if ("L".equals(opeName.substring(0,1))) {
                            etlCellStepV.setStepId(opeName);
//                        }else {
//                            etlCellStepV.setStepId("L"+opeName);
//                        }
//                        if(!StringUtils.isEmpty(o.getDescription())){
//                            if(o.getDescription().length()>60){
//                                etlCellStepV.setStepDesc(o.getDescription().substring(0,60));
//                            }else {
//                                etlCellStepV.setStepDesc(o.getDescription());
//                            }
//                        }else{
//                            etlCellStepV.setStepDesc(OTHER);
//                        }
                        etlCellStepV.setStepDesc(OTHER);
                        if (StringUtils.isEmpty(o.getDetailprocessoperationtype())) {
                            etlCellStepV.setStepGroup(OTHER);
                        } else {
                            etlCellStepV.setStepGroup(o.getDetailprocessoperationtype());
                        }
                        etlCellStepV.setStepType(o.getProcessoperationtype());
                        MesNode mesNode = mesNodeMap.get(opeName);
                        if (null != mesNode && !StringUtils.isEmpty(mesNode.getYcoordinate())) {
                            etlCellStepV.setStepSeq(String.valueOf(mesNode.getYcoordinate()));
                        } else {
                            etlCellStepV.setStepSeq(OTHER);
                        }

                        etlCellStepVList.add(etlCellStepV);
                    }
                }
            });
        }catch (Exception e){
            logger.error(errorProcessArrayStepV+":"+e.getMessage());
            logger.error(LoggerUtil.stackTraceToString(e));
            throw new ETLException(errorProcessArrayStepV+":"+e.getMessage());
        }
        return etlCellStepVList;
    }

    public List<EtlCell2StepV> loadAllFinalStep(String shopName, int errorProcessArrayStepV) throws ETLException {
        List<EtlCell2StepV> etlCellStepV=new ArrayList<>();
        List<EtlCell2StepV> etlMesArrayStepVList=new ArrayList<>();
        try {
            String hql="from MOpeD where ope_id is not null and ope_id <>'' and shopId='"+shopName+"'";
            List<MOpeD> stepList=dao2.find(MOpeD.class,hql);
            etlCellStepV=processBaseDataService.processArrayStep(stepList, ErrorLog.ERROR_PROCESS_ARRAY_STEP_V);

            Map<String, Boolean> opeMap = new HashMap<>();
            stepList.forEach(s -> {
//                if ("L".equals(s.getOpeId().substring(0,1))) {
                    opeMap.put(s.getOpeId(), true);
//                    System.out.println("======="+s.getOpeId());
//                }else {
//                    opeMap.put("L"+s.getOpeId(), true);
//                    System.out.println("==========L"+s.getOpeId());
//                }
            });

            etlMesArrayStepVList = loadAllMesFinalStep(shopName, errorProcessArrayStepV);
            List<EtlCell2StepV> finalEtlCell2StepV = etlCellStepV;
            etlMesArrayStepVList.forEach(s->{
                if (null == opeMap.get(s.getStepId())) {
                    opeMap.put(s.getStepId(), true);
                    finalEtlCell2StepV.add(s);
                }
            });
        }catch (Exception e){
            logger.error(errorProcessArrayStepV+":"+e.getMessage());
            logger.error(LoggerUtil.stackTraceToString(e));
            throw new ETLException(errorProcessArrayStepV+":"+e.getMessage());
        }
        return etlCellStepV;
    }

    public List<MesProductspec> loadAllProduct(String shopName) {
        String hql = "from MesProductspec where PRODUCTIONTYPE IN ('Engineer','Production') ";
        if (!StringUtils.isEmpty(shopName)) {
            hql += " and subfactoryname = '" + shopName + "'";
        }
        return daomes.find(MesProductspec.class, hql);
    }

    public List<EtlCell2ProductV> loadAllFinalProduct(String shopName, int errorProcessArrayProductV) throws ETLException {
        List<MesProductspec> mesProductspecList = loadAllProduct(shopName);
        List<EtlCell2ProductV> etlCfProductVList = new ArrayList<>();
        Map<String, Boolean> productMap = new HashMap<>();

        try {
            mesProductspecList.forEach(p -> {
                String productName = p.getProductspecname();
                if (null == productMap.get(productName)) {
                    productMap.put(productName, true);

                    EtlCell2ProductV etlCfProductV = new EtlCell2ProductV();
                    etlCfProductV.setProductId(p.getProductspecname());
                    etlCfProductV.setProductVersion("00001");
                    String productGroup = OTHER;
                    if (SHOP_OC.equals(p.getSubfactoryname()) &&
                            p.getProductspecname().length() > 4) {
                        if ("L".equals(p.getProductspecname().substring(0, 1))) {
                            productGroup = p.getProductspecname().substring(2, 7);
                        } else {
                            productGroup = p.getProductspecname().substring(1, 6);
                        }
                    } else {
                        productGroup = p.getProductspecname().substring(2, 7);
                    }
                    etlCfProductV.setProductGroup(productGroup);
                    etlCfProductV.setModelName(productGroup);
                    etlCfProductV.setPanelSize(productGroup.substring(0, 3));
                    etlCfProductV.setProductType(p.getProductiontype());
                    etlCfProductV.setPanelQty(p.getProductquantity());
                    etlCfProductV.setProductIdErp(p.getErpproductspecname());

                    etlCfProductVList.add(etlCfProductV);
                }
            });
        }catch (Exception e){
            logger.error(errorProcessArrayProductV+":"+e.getMessage());
            logger.error(LoggerUtil.stackTraceToString(e));
            throw new ETLException(errorProcessArrayProductV+":"+e.getMessage());
        }
        return etlCfProductVList;
    }


    public List<MesProducthistory> loadCommonGlassInfo(EtlConfD etlConfD, String glassId) {
        List<MesProducthistory> mesProducthistoryEntity=new ArrayList<>();
        try {
            StringBuffer hql = new StringBuffer();
            hql.append("FROM MesProducthistory WHERE subfactoryname='").append(etlConfD.getShop()).append("' ")
                    .append(" and PRODUCTNAME ='").append(glassId).append("' ORDER BY TIMEKEY DESC");
            List<MesProducthistory> allCmn=daomes.list(MesProducthistory.class, hql.toString());
            if (allCmn.size()>0) {
                mesProducthistoryEntity.add(allCmn.get(0));
            }
            return mesProducthistoryEntity;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public List<MArrayParamD> loadArrayParamInfo() {
//        try {
        StringBuffer hql = new StringBuffer();
        hql.append("FROM MArrayParamD");
//        hql.append("WHERE param_collection='").append(param_collection).append("' ");
//        hql.append("and param_name='").append(param_name).append("' ");
//            processBaseDataService.processParam();
        return dao2.list(MArrayParamD.class, hql.toString());
//        }catch (Exception e){

//        }

    }



    public List<MArrayParamD> loadParamInfo(String shopName) {
        StringBuffer hql = new StringBuffer();
        hql.append("FROM MParamD where shopName='").append(shopName).append("' ");
        List<MParamD> mParamDS =  dao2.list(MParamD.class, hql.toString());

        List<MArrayParamD> mArrayParamDList = new ArrayList<>();
        mParamDS.forEach(m ->{
            MArrayParamD mArrayParamD = new MArrayParamD();
            BeanUtils.copyProperties(m, mArrayParamD);
            mArrayParamDList.add(mArrayParamD);
        });
        return mArrayParamDList;
    }
}
